import 'package:class_teacher_student/extension/list_section_extension.dart';
import 'package:class_teacher_student/model/Letter.dart';
import 'package:class_teacher_student/page/widget/alphabet_list.dart';
import 'package:class_teacher_student/page/widget/sticky_head.dart';
import 'package:class_teacher_student/util/localization/LocalizationUtil.dart';
import 'package:class_teacher_student/extension/global_key_extension.dart';
import 'package:class_teacher_student/util/log/LogUtil.dart';
import 'package:class_teacher_student/util/mock/mock_test_data.dart';
import 'package:flutter/material.dart';

import '../model/section.dart';
import '../model/student.dart';
import '../util/screen/MonitorUtil.dart';
import '../util/skin/SkinConfig.dart';


class CtsListPage extends StatefulWidget {
  @override
  CtsListPageState createState() => CtsListPageState();
}

class CtsListPageState extends State<CtsListPage> {

  //是否关闭滚动监听
  static bool isScrollListenerDummy=false;
  Function changeSkinCallback;
  List<Section> datas;
  ScrollController _contentController = ScrollController();
  GlobalKey sectionListKey = GlobalKey();
  GlobalKey<StickyHeadState> stickyHeadKey = GlobalKey<StickyHeadState>();
  GlobalKey<AlphabetListState> alphabetListKey = GlobalKey<AlphabetListState>();
  int currentLetterIndex=0;
  List<Letter> letters = Letter.getLetters();

  @override
  void initState() {
    //获取测试数据
    setState(() {
      datas = MockTestData.getDatas().mergeAlphabet();
      LogUtil.d("生成测试数据");
    });

    _contentController.addListener(() {
      if(isScrollListenerDummy)
        return;
      print(_contentController.offset);
      stickyHeadKey.setTop(sectionListKey.y());
      stickyHeadKey.refreshByScroll();
      alphabetListKey.refresh();
    });

    //定义修改颜色的回调
    //包装setstate方法，刷新页面
    changeSkinCallback = (){
      setState((){
      });
    };
    //注册颜色修改回调
    SkinConfig().regChangeAction(changeSkinCallback);
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    //注销修改颜色的回调
    SkinConfig().unRegChangeAction(changeSkinCallback);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    //配置窗口初始适配尺寸
    MonitorUtil.init(context);

    return Scaffold(
      appBar: AppBar(
        title: Text(LocalizationUtil.of(context).appTitle),
      ),
      body: Column(
        children: <Widget>[
           Expanded(
              flex: 0,
              child: Padding(
                padding: EdgeInsets.only(left: 10,right: 10),
                child:Row(
                  children: <Widget>[
                    Expanded(child:TextField(), flex:1),
                      InkWell(
                        child: Text('Search'),
                      )
                    ]
                )
              )
            ),
           Expanded(
              flex: 0,
              child: Padding(
                padding: EdgeInsets.only(left: 10,right: 10,bottom: 10),
                child: Row(
                  children: <Widget>[
                    Expanded(child:TextField(), flex:1),
                    InkWell(
                      child: Text('Test Add/Del'),
                    )
                  ]
              )
            ),
          ),
          Expanded(
            flex: 1,
            child:Stack(
              children: <Widget>[
                _buildSections(),
                _buildAlphabetList(),
                _buildStickySection(),
              ]
            )
          )
        ]
      )
    );

  }

  Widget _buildSections(){
    return Positioned(
      left: 0,
      right:40,
      top:0,
      bottom: 0,
      child:ListView.builder(
          key: sectionListKey,
          controller: _contentController,
          itemBuilder: (BuildContext context, int index) {
            return _buildOneSection(datas[index]);
          },
          itemCount: datas.length,
      )
    );
  }

  Widget _buildOneSection(Section section){
    if(section.isLetter){
      return Padding(
        padding: EdgeInsets.only(left: 10),
        child: Container(
          key: section.key,
          child: Text(section.letter),
          height: Section.heightOfLetter,
          alignment: Alignment.centerLeft,
        )
      );
    }else if(!section.isExpanded) {
      return Container(
        key: section.key,
        child:Row(
          children: [
            Expanded(
              flex: 1,
              child: Text("teacher:${section.tname} & class:${section.cname}"),
            ),
            IconButton(
              icon: Icon(Icons.keyboard_arrow_down),
              onPressed: () {
                setState(() {
                  section.isExpanded = true;
                });
              },
            )
          ],
        ),
        width: MediaQuery.of(context).size.width,
        height: Section.heightOfNormal,
      );
    }else{
      return _buildExpandedSection(section);
    }

//      {
//        return ExpansionTile(
//          key: section.key,
//          title: Text("teacher:${section.tname} & class:${section.cname}"),
//          children: section.students.map((e) => _buildStudent(e)).toList(),
//          onExpansionChanged: (bool value){
//            section.isExpanded=value;
//            print("section高度:${section.key.height()}");
//          },
//        );
//      }

  }

  Widget _buildExpandedSection(Section section){
    List<Widget> widgets = List<Widget>();
    Widget sectionWidget = Container(
      key: section.key,
      child: Row(
        children: [
          Expanded(
            flex: 1,
            child: Text("teacher:${section.tname} & class:${section.cname}"),
          ),
          IconButton(
            icon: Icon(Icons.keyboard_arrow_up),
            onPressed: () {
              setState(() {
                section.isExpanded = false;
              });
            },
          )
        ],
      ),
      width: MediaQuery.of(context).size.width,
      height: Section.heightOfNormal,
    );
    widgets.add(sectionWidget);
    List<Widget> studentWidgets = section.students.map((e) => _buildStudent(e)).toList();
    widgets.addAll(studentWidgets);
    return Column(
      children: widgets,
    );
  }

  Widget _buildStudent(Student student) {
    return Container(
      child: Text("student:${student.sname}"),
      alignment: Alignment.centerLeft,
      height: Student.height,
      width: MediaQuery.of(context).size.width,
    );
  }

  Widget _buildStickySection() {
      return StickyHead(datas, key: stickyHeadKey);
  }

  Widget _buildAlphabetList() {
    return AlphabetList(datas, _contentController, sectionListKey, stickyHeadKey, key: alphabetListKey);
  }

//  Widget _buildAlphabetList(){
//    return Positioned(
//        top: 60,
//        right: 20,
//        bottom: 20,
//        width: 15,
//        child:ListView.builder(
//          itemCount: letters.length,
//          itemBuilder: (BuildContext context, int index) {
//            return GestureDetector(
//              child: Container(
//                height: 20,
//                width: 15,
//                child:Text(
//                  letters[index].character,
//                  style: Letter.currentIndex==index ? TextStyle(color: Colors.black, fontWeight: FontWeight.bold) : TextStyle(color: Colors.grey),
//                )
//              ),
//              onTap: () {
//                double offsetY = 0;
//                double heightOfNormalSection=0;
//                String endLetter=letters[index].character;
//                int curIndex=0;
//
//                letters[index].isSelected=true;
//
//                //获得Expandable Section的高度
//                for(Section section in datas){
//                  if(section.key.currentContext!=null && !section.isLetter){
//                    if(section.isExpanded)
//                      heightOfNormalSection=section.key.height()-section.students.length*Student.height;
//                    else
//                      heightOfNormalSection=section.key.height();
//
//                    break;
//                  }
//                }
//
//                for(var i=0; i<datas.length; i++) {
//                  Section section = datas[i];
//                  if (endLetter == section.letter) {
//                    curIndex=i;
//                    break;
//                  }
//
//                  if(section.isLetter)
//                    offsetY +=Section.heightOfLetter;
//                  else {
//                    if (section.isExpanded) {
//                      offsetY += heightOfNormalSection +
//                          section.students.length * Student.height;
//                    } else {
//                      offsetY += heightOfNormalSection;
//                    }
//                  }
//                }
//
//                _contentController.jumpTo(offsetY);
//                setState(() {
//                  StickyHeadState.currentIndex=curIndex;
//                });
//
//              },
//            );
//          }
//        )
//      );
//    }


}
